import json

import requests
from loguru import logger

from ai_engine.core.llm.volcengine.ark_common import ArkException


class ArkService(object):

    def __init__(self, ak, sk):
        self.ak = ak
        self.sk = sk

    def json_exception(self, url, headers, body):
        try:
            res = self.post_json(url, headers, body)
        except Exception as e:
            try:
                res_json = json.loads(e.args[0].decode("utf-8"))
            except Exception as ee:
                raise ArkException(1000028, "missed", "json load res error, res:{}".format(str(e))) from None
            code = res_json.get("code", 1000028)
            request_id = res_json.get("request_id", 1000028)
            message = res_json.get("message", None)
            logger.error("生成向量异常:body:{},error:{}".format(body, str(e)))
            raise ArkException(code, request_id, message)
        if res == '':
            raise ArkException(1000028, "missed",
                               "empty response due to unknown error, please contact customer service") from None
        return res

    def post_json(self, url, headers, body):
        # 设置连接超时为5秒，读取超时为10秒
        timeout = (5, 15)
        resp = requests.request(method="POST",
                                url=url,
                                headers=headers,
                                data=body,
                                timeout=timeout
                                )
        if resp.status_code == 200:
            return json.dumps(resp.json())
        else:
            raise Exception(resp.text.encode("utf-8"))
